<template>
  <div class="chat-container nav-bar-top">
    <van-nav-bar class="nav-bar" title="咨询服务" left-arrow @click-left="$router.back()"/>
    <ul class="chat-content" id="chatBox">
       <li v-for="(item, index) in messageList" :key="index">
          <div class="sys-msg" v-if="item.type == 'sys'">
            <div class="msg">
              <span>{{item.msg}}</span>
            </div>
          </div>
          <div class="dialog-msg" v-if="item.type == 'dialogStart'">
            <div class="msg">
              <span>{{item.msg}}</span>
            </div>
          </div>
          <div class="dialog-msg" v-if="item.type == 'dialogStop'">
            <div class="msg">
              <span>{{item.msg}}</span>
            </div>
          </div>
          <div class="text-msg receive-msg" v-if="item.userType == 'staff'">
            <van-image src="imgs/staff.png"/>
            <div class="msg-box">
              <div class="user">
                <span class="name">{{'客服 '+item.from}}</span>
                <span class="time">{{item.createTime | time}}</span>
              </div>
              <div class="msg">
                <span>{{item.msg}}</span>
              </div>
            </div>
          </div>
          <div class="text-msg send-msg" v-if="item.userType == 'user'">
            <div class="msg-box">
              <div class="user">
                <span class="time">{{item.createTime | time}}</span>
                <span class="name">{{user.name}}</span>
              </div>
              <div class="msg">
                <span>{{item.msg}}</span>
              </div>
            </div>
            <van-image :src="user && user.headUrl ? user.headUrl : 'imgs/user/avatar.png'"/>
          </div>
       </li>
    </ul>
    <div class="chat-btn-box">
      <div class="chat-input">
        <van-field
          class="message"
          v-model="message"
          type="input"
          placeholder=""
        />
      </div>
      <div class="chat-btn">
        <van-icon name="add-o"/>
        <van-button @click="sendMessage">发送</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default{
  name: 'chat',
  data () {
    return{
      webSocket: null,
      messageList: [],
      message: '',
      to: ''
    }
  },
  computed: {
    ...mapState(['user'])
  },
  created () {
    this.initWebSocket();
  },
  methods: {
    //连接webSocket
    initWebSocket () {
      this.webSocket = new WebSocket("ws://www.mvvm.site:8850/ws");
      this.webSocket.onopen = this.onOpen;
      this.webSocket.onclose = this.onClose;
      this.webSocket.onerror = this.onError;
      this.webSocket.onmessage = this.onMsg;
    },
    onOpen () {
      this.webSocket.send(JSON.stringify({type: 'connectStart',uid: this.user.id, userType: 'user', createTime: new Date()}));
      console.log("连接打开!")
    },
    onClose () {
      console.log("连接关闭!")
    },
    onError () {
      console.log("连接错误!")
    },
    onMsg (event) {
      console.log("收到消息："+event.data)
      var data = JSON.parse(event.data);
      if(data.type == "dialogStart"){
        this.to = data.to;
      }
      this.messageList.push(JSON.parse(event.data))
      this.$nextTick(() => {
        let msg = document.getElementById('chatBox') // 获取对象
        msg.scrollTop = msg.scrollHeight // 滚动高度
      })
    },
    //发送消息
    sendMessage () {
      if(this.message){
        var msg = {type: 'text', userType: 'user', from: this.user.id, to:this.to, msg: this.message, createTime: new Date()};
        //发送消息
        this.webSocket.send(JSON.stringify(msg))
        //放入聊天框
        this.messageList.push(msg)
        //清空输入框
        this.message = ''
        this.$nextTick(() => {
          let msg = document.getElementById('chatBox') // 获取对象
          msg.scrollTop = msg.scrollHeight // 滚动高度
        })
      }
    }
  }
}
</script>

<style lang="scss">
.chat-container{
  padding-top: 5px;
  padding-bottom: 80px;
  .chat-content{
    height: calc(100vh - 120px);
    overflow: auto;
  }
  .sys-msg, .dialog-msg{
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10px 0px;
    .msg{
      display: flex;
      justify-content: center;
      align-items: center;
      background: #ccc;
      padding: 5px 10px;
      border-radius: 5px;
      span{
        font-size: 13px;
        color: #fff;
      }
    }
  }
  .text-msg{
    display: flex;
    align-items: baseline;
    padding: 10px 10px;
    .van-image{
      img{
        border-radius: 50%;
        height: 30px;
        width: 30px;
      }
    }
    .msg-box{
      position: relative;
      top: -10px;
      display: flex;
      flex-direction: column;
      justify-content: flex-end;
      .user{
        color: #999;
        font-size: 12px;
        margin-bottom: 10px;
      }
      .msg{
        display: flex;
        align-items: center;
        word-wrap: break-word;
        word-break: break-all;
        span{
          background: #fff;
          padding: 5px 10px;
          border-radius: 10px;
          line-height: 24px;
          font-size: 14px;
          color: #333;
        }
      }
    }
  }
  .receive-msg{
    justify-content: flex-start;
    .van-image{
      margin-right: 10px;
    }
    .msg-box{
      .user{
        .name{
          margin-right: 10px;
        }
      }
      .msg{
        justify-content: flex-start;
      }
    }
  }
  .send-msg{
    justify-content: flex-end;
    .van-image{
      margin-left: 10px;
    }
    .msg-box{
      .user{
        .name{
          margin-left: 10px;
        }
      }
      .msg{
        justify-content: flex-end;
      }
    }
  }
  .chat-btn-box{
    z-index: 2;
    background: #f0f0f0;
    position: fixed;
    bottom: 0;
    left: 0;
    width: calc(100% - 20px);
    height: 70px;
    display: flex;
    align-items: center;
    padding: 0 10px;
    border-top: 1px solid #f6f6f6;
    .chat-input{
      flex: 1;
      display: flex;
      align-items: center;
      .van-field{
        border-radius: 10px;
        padding: 7px 10px;
      }
    }
    .chat-btn{
      height: 40px;
      margin-left: 10px;
      width: 110px;
      display: flex;
      align-items: center;
      .van-icon{
        font-size: 26px;
        margin: 0px 8px;
      }
      .van-button{
        height: 37px;
        width: 80px;
      }
    }
  }
}
</style>
